<template>
  <view v-if="visible" class="modal-overlay" @click="handleOverlayClick">
    <view class="popup-content" @click.stop>
      <view class="popup-header">
        <text class="popup-title">{{ isEditMode ? '编辑商品' : '创建商品' }}</text>
        <view class="popup-close" @click="closeModal">
          <uni-icons type="close" size="20" color="#666"></uni-icons>
        </view>
      </view>
      
      <view class="popup-body">
        <view class="form-item">
          <text class="form-label">商品名称 <text class="required">*</text></text>
          <input 
            class="form-input" 
            v-model="formData.name" 
            placeholder="请输入商品名称"
            :class="{ 'error': errors.name }"
          />
          <text v-if="errors.name" class="error-text">{{ errors.name }}</text>
        </view>
        
        <view class="form-item">
          <text class="form-label">商品价格 <text class="required">*</text></text>
          <input 
            class="form-input" 
            v-model="formData.price" 
            placeholder="请输入商品价格"
            type="digit"
            :class="{ 'error': errors.price }"
          />
          <text v-if="errors.price" class="error-text">{{ errors.price }}</text>
        </view>
        
        <view class="form-item">
          <text class="form-label">库存数量 <text class="required">*</text></text>
          <input 
            class="form-input" 
            v-model="formData.totalStock" 
            placeholder="请输入库存数量"
            type="number"
            :class="{ 'error': errors.totalStock }"
          />
          <text v-if="errors.totalStock" class="error-text">{{ errors.totalStock }}</text>
        </view>
        
        <view class="form-item">
          <text class="form-label">安全库存 <text class="required">*</text></text>
          <input 
            class="form-input" 
            v-model="formData.safeStock" 
            placeholder="请输入安全库存"
            type="number"
            :class="{ 'error': errors.safeStock }"
          />
          <text v-if="errors.safeStock" class="error-text">{{ errors.safeStock }}</text>
        </view>
        
        <view class="form-item">
          <text class="form-label">商品分类 <text class="required">*</text></text>
          <picker 
            :value="getCategoryIndex(formData.categoryId)" 
            :range="categories" 
            range-key="name"
            @change="onCategoryChange"
          >
            <view class="form-input picker-input" :class="{ 'error': errors.categoryId }">
              {{ getCategoryName(formData.categoryId) || '请选择商品分类' }}
              <uni-icons type="down" size="16" color="#999"></uni-icons>
            </view>
          </picker>
          <text v-if="errors.categoryId" class="error-text">{{ errors.categoryId }}</text>
        </view>
        
        <view class="form-item">
          <text class="form-label">商品图片</text>
          <view class="image-upload-section">
            <view class="image-preview" v-if="formData.imageUrl">
              <image :src="formData.imageUrl" mode="aspectFill" class="preview-image"></image>
              <view class="remove-image" @click="removeImage">
                <uni-icons type="close" size="16" color="#fff"></uni-icons>
              </view>
            </view>
            <view v-else class="upload-placeholder" @click="chooseImage">
              <uni-icons type="camera" size="32" color="#999"></uni-icons>
              <text class="upload-text">点击上传图片</text>
            </view>
          </view>
        </view>
        
        <view class="form-item">
          <text class="form-label">商品描述</text>
          <textarea 
            class="form-textarea" 
            v-model="formData.description" 
            placeholder="请输入商品描述（可选）"
            maxlength="500"
          />
          <view class="char-count">{{ formData.description?.length || 0 }}/500</view>
        </view>
      </view>
      
      <view class="popup-footer">
        <view class="cancel-btn" @click="closeModal">取消</view>
        <view 
          class="submit-btn" 
          :class="{ 'loading': isSubmitting }"
          @click="handleSubmit"
        >
          <uni-icons v-if="isSubmitting" type="spinner-cycle" size="16" color="#fff"></uni-icons>
          <text>{{ isSubmitting ? '提交中...' : (isEditMode ? '更新' : '创建') }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue';

// Props - Fixed prop name to match parent component
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  'product-data': {  // Changed from productData to product-data
    type: Object,
    default: () => ({})
  },
  categories: {
    type: Array,
    default: () => []
  },
  'is-edit-mode': {  // Changed from isEditMode to is-edit-mode
    type: Boolean,
    default: false
  }
});

// Emits
const emit = defineEmits(['close', 'submit']);

// Form data
const formData = reactive({
  id: null,
  name: '',
  price: '',
  totalStock: '',
  safeStock: '',
  categoryId: null,
  description: '',
  imageUrl: ''
});

// Form validation errors
const errors = reactive({
  name: '',
  price: '',
  totalStock: '',
  safeStock: '',
  categoryId: ''
});

// Loading state
const isSubmitting = ref(false);

// Computed properties for accessing kebab-case props
const productData = computed(() => props['product-data']);
const isEditMode = computed(() => props['is-edit-mode']);

// Watch for product data changes
watch(() => productData.value, (newData) => {
  if (newData && Object.keys(newData).length > 0) {
    formData.id = newData.id;
    formData.name = newData.name || '';
    formData.price = newData.price?.toString() || '';
    formData.totalStock = newData.totalStock?.toString() || '';
    formData.safeStock = newData.safeStock?.toString() || '';
    formData.categoryId = newData.categoryId || null;
    formData.description = newData.description || '';
    formData.imageUrl = newData.mainImageUrl || '';
  }
}, { immediate: true });

// Watch for modal visibility changes
watch(() => props.visible, (visible) => {
  if (!visible) {
    resetForm();
  }
});

// Get category name
const getCategoryName = (categoryId) => {
  if (!categoryId) return '';
  const category = props.categories.find(c => c.id === categoryId);
  return category ? category.name : '';
};

// Get category index for picker
const getCategoryIndex = (categoryId) => {
  const index = props.categories.findIndex(c => c.id === categoryId);
  return index >= 0 ? index : 0;
};

// Handle category change
const onCategoryChange = (e) => {
  const index = e.detail.value;
  formData.categoryId = props.categories[index].id;
  errors.categoryId = '';
};

// Choose image
const chooseImage = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      formData.imageUrl = res.tempFilePaths[0];
    },
    fail: (err) => {
      console.error('选择图片失败:', err);
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      });
    }
  });
};

// Remove image
const removeImage = () => {
  formData.imageUrl = '';
};

// Validate form
const validateForm = () => {
  let isValid = true;
  
  // Reset errors
  Object.keys(errors).forEach(key => {
    errors[key] = '';
  });
  
  // Validate name
  if (!formData.name.trim()) {
    errors.name = '请输入商品名称';
    isValid = false;
  }
  
  // Validate price
  if (!formData.price || parseFloat(formData.price) <= 0) {
    errors.price = '请输入有效的商品价格';
    isValid = false;
  }
  
  // Validate total stock
  if (!formData.totalStock || parseInt(formData.totalStock) < 0) {
    errors.totalStock = '请输入有效的库存数量';
    isValid = false;
  }
  
  // Validate safe stock
  if (!formData.safeStock || parseInt(formData.safeStock) < 0) {
    errors.safeStock = '请输入有效的安全库存';
    isValid = false;
  }
  
  // Validate category
  if (!formData.categoryId) {
    errors.categoryId = '请选择商品分类';
    isValid = false;
  }
  
  return isValid;
};

// Handle form submission
const handleSubmit = async () => {
  if (!validateForm()) {
    return;
  }
  
  isSubmitting.value = true;
  
  try {
    const submitData = {
      id: formData.id,
      name: formData.name.trim(),
      price: parseFloat(formData.price),
      totalStock: parseInt(formData.totalStock),
      safeStock: parseInt(formData.safeStock),
      categoryId: formData.categoryId,
      description: formData.description.trim(),
      imageUrl: formData.imageUrl
    };
    
    emit('submit', submitData);
  } catch (error) {
    console.error('表单提交失败:', error);
  } finally {
    isSubmitting.value = false;
  }
};

// Handle overlay click
const handleOverlayClick = () => {
  closeModal();
};

// Close modal
const closeModal = () => {
  emit('close');
};

// Reset form
const resetForm = () => {
  formData.id = null;
  formData.name = '';
  formData.price = '';
  formData.totalStock = '';
  formData.safeStock = '';
  formData.categoryId = null;
  formData.description = '';
  formData.imageUrl = '';
  
  Object.keys(errors).forEach(key => {
    errors[key] = '';
  });
  
  isSubmitting.value = false;
};
</script>

<style>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.popup-content {
  width: 650rpx;
  max-height: 85vh;
  background-color: #FFFFFF;
  border-radius: 20rpx;
  overflow: hidden;
  margin: 0 50rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.3);
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #FFE6CC;
  background-color: #FFF9F2;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.popup-close {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 30rpx;
  background-color: #F5F5F5;
}

.popup-body {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.popup-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-top: 1rpx solid #FFE6CC;
  background-color: #FFF9F2;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 10rpx;
  font-weight: 500;
}

.required {
  color: #FF4444;
}

.form-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #DDDDDD;
  border-radius: 10rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: #FFFFFF;
  transition: border-color 0.3s;
}

.form-input:focus {
  border-color: #FF8C42;
  outline: none;
}

.form-input.error {
  border-color: #FF4444;
}

.picker-input {
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #333333;
}

.form-textarea {
  width: 100%;
  min-height: 120rpx;
  border: 1rpx solid #DDDDDD;
  border-radius: 10rpx;
  padding: 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  resize: none;
  background-color: #FFFFFF;
  transition: border-color 0.3s;
}

.form-textarea:focus {
  border-color: #FF8C42;
  outline: none;
}

.char-count {
  text-align: right;
  font-size: 24rpx;
  color: #999999;
  margin-top: 10rpx;
}

.error-text {
  font-size: 24rpx;
  color: #FF4444;
  margin-top: 10rpx;
  display: block;
}

.image-upload-section {
  margin-top: 10rpx;
}

.image-preview {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border-radius: 10rpx;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-image {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.upload-placeholder {
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #DDDDDD;
  border-radius: 10rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #FAFAFA;
}

.upload-text {
  font-size: 24rpx;
  color: #999999;
  margin-top: 10rpx;
}

.cancel-btn {
  padding: 16rpx 40rpx;
  background-color: #F5F5F5;
  color: #666666;
}